package work823;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.Scanner;

public class work5Server {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    byte[] buf = new byte[1024];
    try {
      //创建DatagramPacket对象，用来准备接受数据包
      DatagramPacket dp = new DatagramPacket(buf,1024);
      //创建DatagramSocket对象，接受数据
      DatagramSocket ds = new DatagramSocket(8888);
     while (true){
       ds.receive(dp);
       //显示收到的信息
       String str = new String(dp.getData(),0,dp.getLength());
       System.out.println(dp.getAddress().getHostAddress()+"说："+str);
         System.out.println("输入回应消息");
         String str2 = sc.next();
         //创建DatagramPacket对象，封装数据
         SocketAddress sa = dp.getSocketAddress();
         DatagramPacket dp2 = new DatagramPacket(str2.getBytes(),str2.getBytes().length,sa);
         ds.send(dp2);
       if (str.equals("bye")){
         ds.close();
       }
     }
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
